import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'
const hostname=window.location.hostname
import isString from 'lodash/isString'
import isArray from 'lodash/isArray'
import store from "@/store";
import router from '@/router'
import {resetRouter} from '@/router'
import {noLoadingUrl,noReplaceUrl} from '@/api/config'
if(['localhost'].includes(hostname)){
    window.baseURL='http://172.24.29.21:3000'
}
const service =axios.create({
    baseURL: window.baseURL,
    withCredentials: true,
    timeout: 1000*10,
    validateStatus: function (status) {
        return status >= 200 && status <= 500 // 默认的
    }
})
// HTTPrequest拦截
service.interceptors.request.use(config => {
    let apiUrl=config.url;
    if(!noLoadingUrl.includes(apiUrl)){
        store.commit('exclude/SET_LOADING',true)
    }
    const Authorization=store.getters.userInfo.authorization
    if(Authorization){
        config.headers.Authorization=Authorization
    }
    const reqConfig = {...config}
    // 参数容错
    let params=reqConfig.data || reqConfig.params || {}
    //去除所有空格
    !noReplaceUrl.includes(apiUrl) && Object.keys(params).map(k=>{
        if(isString(params[k])){
            params[k]=params[k].replace(/\s/g,"")
        }else if (isArray(params[k])){
            params[k]=params[k].map(i=>isString(i)?i.replace(/\s/g,""):i)
        }
    })
    if (reqConfig.method === 'get') {
        if (!reqConfig.params) {
            // 防止字段用错
            reqConfig.params = reqConfig.data || {}
        }
    } else if (['post','delete','put'].includes(reqConfig.method)) {
        if (!reqConfig.data) {
            // 防止字段用错
            reqConfig.data = reqConfig.params || {}
        }
        // 检测是否包含文件类型, 若包含则进行 formData 封装
        if(reqConfig.method==='post'){
            let hasFile = false
            Object.keys(reqConfig.data).forEach(key => {
                if (typeof reqConfig.data[key] === 'object') {
                    const item = reqConfig.data[key]
                    if (item instanceof FileList || item instanceof File || item instanceof Blob) {
                        hasFile = true
                    }
                }
            })
            // 检测到存在文件使用 FormData 提交数据
            if (hasFile) {
                const formData = new FormData()
                Object.keys(reqConfig.data).forEach(key => {
                    formData.append(key, reqConfig.data[key])
                })
                reqConfig.data = formData
            }
        }
    }
    return reqConfig
}, error => {
    return Promise.reject(error)
})

// HTTPresponse拦截
service.interceptors.response.use(res => {
    store.commit('exclude/SET_LOADING',false)
    if (res.status.toString().charAt(0) === '2') {
        let {code, msg} = res.data
        if(code){
            Vue.prototype.$message({
                message:msg,
                type: 'error',
            })
            if(code===401){
                setTimeout(()=>{
                    resetRouter();
                    store.dispatch('user/loginOut')
                    router.replace('/login');
                },store.getters.waitTime)
            }
            return Promise.reject(res.data)
        }
        return res.data
    }
    return Promise.reject(res.data)
}, error => {
    store.commit('exclude/SET_LOADING',false)
    if (!error.response) {
        Vue.prototype.$message({
            type: 'error',
            message: '请检查 API 是否异常',
        })
    }

    // 判断请求超时
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
        Vue.prototype.$message({
            type: 'warning',
            message: '请求超时',
        })
    }
    return Promise.reject(error)
})
// 导出常用函数

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 * options{object} {handleError:false,showBackend:true}
 */
export function apiPost(url, data = {},options={}) {
    return service({
        method: 'post',
        url,
        data,
        ...options
    })
}

/**
 * @param {string} url
 * @param {object} params
 */
export function apiGet(url, params = {},options={}) {
    return service({
        method: 'get',
        url,
        params,
        ...options
    })
}


export default service
